/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.Actions;
import org.ipo.mm.ejb.entities.Meeting;
import org.ipo.mm.ejb.facade.actions.ActionsFacadeLocal;
import org.ipo.mm.web.formbeans.ActionBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;

/**
 *
 * @author makcro
 */
public class ActionsCrud extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {



        ActionForward actionForward = null;
        if (isCancelled(request)) {
            actionForward = mapping.findForward(ConstantManager.NAVIGATION_CLOSE_WINDOW);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);

        } else {

            ActionBean actionBean = (ActionBean) form;


            MessageResources mResources = getResources(request);
            String saveOperaton = mResources.getMessage(getLocale(request), "gen_create");
            String updateOperation = mResources.getMessage(getLocale(request), "gen_update");

            String operation = actionBean.getOperation();


            if (saveOperaton.equals(operation)) {
                actionForward = executeCreate(actionBean, request, mapping);
            } else if (updateOperation.equals(operation)) {
                actionForward = executeUpdate(actionBean, request, mapping);
            }


        }


        return actionForward;
    }

    private ActionsFacadeLocal lookupActionsFacade() {
        try {
            Context c = new InitialContext();
            return (ActionsFacadeLocal) c.lookup("java:comp/env/ActionsFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private void notifyOperatoinStatus(String operationMessageKey, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), ConstantManager.ACTIONS_ENTITY_NAME_RES_KEY);

        ActionMessages messages = new ActionMessages();
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);
        messages.add("operation_status", actionMessage);
        saveMessages(request, messages);

    }

    private ActionForward executeCreate(ActionBean actionBean, HttpServletRequest request, ActionMapping mapping) throws Exception {

        ActionForward actionForward = null;

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);

        String actionDesc = actionBean.getActionDesc();
        String actionDueDate = actionBean.getActionDueDate();
        String actionName = actionBean.getActionName();
        String actionStatus = actionBean.getActionStatus();

        Actions actions = new Actions();
        actions.setActionText(actionDesc);
        actions.setDeleted(Boolean.FALSE);
        actions.setDueDate(new SimpleDateFormat("dd/MM/yyyy").parse(actionDueDate));
        actions.setName(actionName);
        actions.setStatus(actionStatus);
        actions.setMeetingId(meeting);






        meeting.getMeetingActions().add(actions);


        actionForward = mapping.findForward(ConstantManager.NAVIGATION_CLOSE_WINDOW);

        return actionForward;
    }

    private ActionForward executeUpdate(ActionBean actionBean, HttpServletRequest request, ActionMapping mapping) throws Exception {
        ActionForward actionForward = null;

        String actionDesc = actionBean.getActionDesc();
        String actionDueDate = actionBean.getActionDueDate();
        String actionName = actionBean.getActionName();
        String actionStatus = actionBean.getActionStatus();

        Date dueDate = new SimpleDateFormat("dd/MM/yyyy").parse(actionDueDate);


        /**
         * determine if request came from actions list, or from meeting update page.
         * if from actions list then retreive action form session atr
         * if from meeting update then get action from collection attached to meeting
         *
         */
        Actions actionsForUpdate = (Actions) request.getSession().getAttribute(ConstantManager.SESSION_ACTIONS_PROCESS);
        actionsForUpdate.setActionText(actionDesc);
        actionsForUpdate.setDueDate(dueDate);
        actionsForUpdate.setName(actionName);
        actionsForUpdate.setStatus(actionStatus);

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);

        if (meeting != null) {
//            Collection<Actions> actionsCollection = meeting.getMeetingActions();
//
//            Iterator<Actions> iterator = actionsCollection.iterator();
//            while (iterator.hasNext()) {
//                Actions actions = iterator.next();
//                if (actions.equals(actionsForUpdate)) {
//                    actions = actionsForUpdate;
//
//                }
//            }
//
//
//


        } // find actions in meeting collection
        else {
            lookupActionsFacade().edit(actionsForUpdate);
            request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        }

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);

        actionForward = mapping.findForward(ConstantManager.NAVIGATION_CLOSE_WINDOW);

        return actionForward;
    }

    private ActionForward executeDelete(HttpServletRequest request, ActionMapping mapping, String actionId) {
        Actions actions = lookupActionsFacade().find(Integer.parseInt(actionId));
        if (actions != null) {
            lookupActionsFacade().remove(actions);
        }

        BreadCrumbs breadCrumbs = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        return breadCrumbs.pop().getActionForward();

    }
}
